from flask import Blueprint, request, jsonify, session
from models import db
from models.ScoreWeight import ScoreWeight
from models.Company import Company
from decimal import Decimal

score_weight_bp = Blueprint('score_weight', __name__)

@score_weight_bp.route('/score-weights', methods=['GET'])
def get_score_weights():
    """获取当前公司的分数权重"""
    if 'user_id' not in session or session['role'] != 'company':
        return jsonify({'error': '未授权访问'}), 401
    
    # 先获取公司信息
    company = Company.query.filter_by(user_id=session['user_id']).first()
    if not company:
        return jsonify({'error': '未找到公司信息'}), 404
    
    weights = ScoreWeight.query.filter_by(company_id=company.company_id).first()
    
    if not weights:
        return jsonify({
            'technical_weight': 0.40,
            'learning_weight': 0.20,
            'team_weight': 0.15,
            'problem_solving_weight': 0.15,
            'communication_weight': 0.10
        })
    
    return jsonify({
        'technical_weight': float(weights.technical_weight),
        'learning_weight': float(weights.learning_weight),
        'team_weight': float(weights.team_weight),
        'problem_solving_weight': float(weights.problem_solving_weight),
        'communication_weight': float(weights.communication_weight)
    })

@score_weight_bp.route('/score-weights', methods=['POST', 'PUT'])
def update_score_weights():
    """更新或创建分数权重"""
    if 'user_id' not in session or session['role'] != 'company':
        return jsonify({'error': '未授权访问'}), 401
    
    # 先获取公司信息
    company = Company.query.filter_by(user_id=session['user_id']).first()
    if not company:
        return jsonify({'error': '未找到公司信息'}), 404
    
    data = request.json
    
    # 验证权重总和是否为1
    total_weight = sum(float(data.get(k, 0)) for k in [
        'technical_weight', 'learning_weight', 'team_weight',
        'problem_solving_weight', 'communication_weight'
    ])
    
    if abs(total_weight - 1.0) > 0.001:  # 允许小误差
        return jsonify({'error': '所有权重之和必须等于1'}), 400
    
    weights = ScoreWeight.query.filter_by(company_id=company.company_id).first()
    
    if not weights:
        weights = ScoreWeight(company_id=company.company_id)
        db.session.add(weights)
    
    # 更新权重
    weights.technical_weight = Decimal(str(data.get('technical_weight', 0.40)))
    weights.learning_weight = Decimal(str(data.get('learning_weight', 0.20)))
    weights.team_weight = Decimal(str(data.get('team_weight', 0.15)))
    weights.problem_solving_weight = Decimal(str(data.get('problem_solving_weight', 0.15)))
    weights.communication_weight = Decimal(str(data.get('communication_weight', 0.10)))
    
    try:
        db.session.commit()
        return jsonify({'message': '权重更新成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@score_weight_bp.route('/save-weights', methods=['POST'])
def save_weights():
    """保存分数权重"""
    if 'user_id' not in session or session['role'] != 'company':
        return jsonify({'error': '未授权访问'}), 401

    # 获取公司信息
    company = Company.query.filter_by(user_id=session['user_id']).first()
    if not company:
        return jsonify({'error': '未找到公司信息'}), 404
    
    data = request.json
    
    # 验证 job_id 是否存在
    job_id = data.get('job_id')
    if not job_id:
        return jsonify({'error': '缺少 job_id 参数'}), 400
    
    try:
        # 确保job_id是整数
        job_id = int(job_id)
        
        # 收集五个权重值
        weights_data = data.get('weights', [])
        
        # 创建权重字典
        weight_dict = {}
        for weight in weights_data:
            name = weight.get('name')
            value = weight.get('value')
            if name and value is not None:
                weight_dict[name] = Decimal(str(value)).quantize(Decimal('0.01'))
        
        # 检查是否有所有必需的权重
        required_weights = ['专业能力', '学习能力', '团队协作', '问题解决', '沟通表达']
        missing_weights = [w for w in required_weights if w not in weight_dict]
        
        if missing_weights:
            return jsonify({'error': f'缺少以下权重值: {", ".join(missing_weights)}'}), 400
        
        # 验证总和是否为1
        total = sum(weight_dict.values())
        if abs(total - Decimal('1.00')) > Decimal('0.01'):
            return jsonify({'error': f'权重总和必须为1，当前总和为{total}'}), 400
        
        # 获取或创建 ScoreWeight 记录
        weight_record = ScoreWeight.query.filter_by(job_id=job_id).first()
        
        if not weight_record:
            weight_record = ScoreWeight(job_id=job_id)
            db.session.add(weight_record)
        
        # 更新权重
        weight_record.technical_weight = weight_dict['专业能力']
        weight_record.learning_weight = weight_dict['学习能力']
        weight_record.team_weight = weight_dict['团队协作']
        weight_record.problem_solving_weight = weight_dict['问题解决']
        weight_record.communication_weight = weight_dict['沟通表达']
        
        db.session.commit()
        return jsonify({'message': '权重保存成功', 'success': True})
    except ValueError:
        return jsonify({'error': 'job_id 必须是整数'}), 400
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@score_weight_bp.route('/get-weights', methods=['GET'])
def get_weights():
    """根据职位ID获取权重配置"""
    job_id = request.args.get('job_id')
    if not job_id:
        return jsonify({'error': '缺少 job_id 参数'}), 400

    try:
        job_id = int(job_id)
        weight_record = ScoreWeight.query.filter_by(job_id=job_id).first()
        
        if not weight_record:
            # 返回默认权重值
            return jsonify({
                'weights': [
                    {'name': '专业能力', 'value': 0.40},
                    {'name': '学习能力', 'value': 0.20},
                    {'name': '团队协作', 'value': 0.15},
                    {'name': '问题解决', 'value': 0.15},
                    {'name': '沟通表达', 'value': 0.10}
                ]
            })
        
        # 返回数据库中的权重值
        weights = [
            {'name': '专业能力', 'value': float(weight_record.technical_weight)},
            {'name': '学习能力', 'value': float(weight_record.learning_weight)},
            {'name': '团队协作', 'value': float(weight_record.team_weight)},
            {'name': '问题解决', 'value': float(weight_record.problem_solving_weight)},
            {'name': '沟通表达', 'value': float(weight_record.communication_weight)}
        ]
        
        return jsonify({'weights': weights})
    except ValueError:
        return jsonify({'error': 'job_id 必须是整数'}), 400
    except Exception as e:
        return jsonify({'error': str(e)}), 500
